package d;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;


public class ConnectionManager {
	private final static String URL = "jdbc:mysql://localhost/fdurmb?user=root&password=root";

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(URL);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static Connection getConnection(int level) {
		Connection conn = getConnection();
		try {
			conn.setTransactionIsolation(level);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	public static void freeConnection(Connection conn) {
		try {
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static <T> T executeQuery(String sql,QueryCallback<T> cb,Object... params) {
		Connection conn = getConnection();
		T retVal = null;
		try {
			conn.setReadOnly(true);
			PreparedStatement ps = conn.prepareStatement(sql);
			setPreparedParams(ps,params);
			retVal = cb.processResultset(ps.executeQuery());
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			freeConnection(conn);
		}
		return retVal;
	}

	public static boolean executeUpdate(String sql,Object... params) {
		boolean retval = false;
		Connection conn = getConnection();

		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			setPreparedParams(ps,params);
			if(ps.executeUpdate()>0) {
				retval = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			freeConnection(conn);
		}

		return retval;
	}

	private static void setPreparedParams(PreparedStatement ps,Object... params) throws SQLException {
		int paramCnt = 1;
		for(Object p:params){
			ps.setObject(paramCnt++, p);
		}
	}
}
